package com.example.cloud.service.business.medical.impl;

import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.ExecuteRecordRepository;
import com.example.cloud.dao.statistics.StatisticsFinancialRepository;
import com.example.cloud.model.business.medical.ExecuteRecord;
import com.example.cloud.model.statistics.StatisticsFinancial;
import com.example.cloud.model.system.User;
import com.example.cloud.service.business.medical.ExecuteService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class ExecuteServiceImpl implements ExecuteService {

    private static final Logger logger = Logger.getLogger(ExecuteServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    SQLManager sqlManager;

    @Autowired
    private ExecuteRecordRepository executeRecordRepository;

    @Autowired
    private StatisticsFinancialRepository statisticsFinancialRepository;

    @Override
    @Transactional
    public void doSave(ExecuteRecord record) {
        // 保存
        executeRecordRepository.save(record);
        // 统计治疗人次
        User u = RequestUtil.getLoginUser();
        StringBuilder sql = new StringBuilder("select * from statistics_financial where user_id = :id and DATE_FORMAT(creation_time,'%Y-%m-%d') = :time");
        Query nq = em.createNativeQuery(sql.toString(), StatisticsFinancial.class);
        nq.setParameter("id", u.getId());
        nq.setParameter("time", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        List<StatisticsFinancial> rs = nq.getResultList();
        if(!rs.isEmpty()){
            sql = new StringBuilder("update statistics_financial set treat_transaction = treat_transaction + 1 where id = :id");
            nq = em.createNativeQuery(sql.toString());
            nq.setParameter("id", rs.get(0).getId());
            nq.executeUpdate();
        }else{
            StatisticsFinancial sf = new StatisticsFinancial();
            sf.setUserId(u.getId());
            sf.setUserName(u.getUsername());
            sf.setTreatTransaction(1);
            sf.setAccountId(u.getAccountId());
            sf.setOrganId(u.getOrganId());
            sf.setOrganName(u.getOrganName());
            BusinessUtil.appendRecord(sf);
            statisticsFinancialRepository.save(sf);
        }
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 执行数据
        List<ExecuteRecord> records = executeRecordRepository.findByIdIn(ids);
        // 删除执行记录
        executeRecordRepository.deleteByIdIn(ids);
        // 更新执行次数
        StringBuilder sql = null;
        Query nq = null;
        for (ExecuteRecord record : records) {
            int count = executeRecordRepository.countByOrderIdAndDeleteFlag(record.getOrderId(), 0);
            if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_ONE && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PROJECT){
                sql = new StringBuilder("update treat_plan_project set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }else if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_ONE && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PRODUCT){
                sql = new StringBuilder("update treat_plan_product set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }else if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_COURSE && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PROJECT){
                sql = new StringBuilder("update treat_plan_course_details set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }else if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_COURSE && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PRODUCT){
                sql = new StringBuilder("update treat_plan_course_product set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }else if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_HOME && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PROJECT){
                sql = new StringBuilder("update treat_plan_home_project set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }else if(record.getTreatType() == StateConstants.EXECUTE_TREAT_TYPE_HOME && record.getItemType() == StateConstants.EXECUTE_ITEM_TYPE_PRODUCT){
                sql = new StringBuilder("update treat_plan_home_product set `execute` = :execute where id = :id");
                nq = em.createNativeQuery(sql.toString());
            }
            nq.setParameter("execute", count);
            nq.setParameter("id", record.getOrderId());
            nq.executeUpdate();

            // 财务治疗次数统计
            sql = new StringBuilder("select id from statistics_financial");
            sql.append(" where user_id = " + RequestUtil.getLoginUser().getId());
            sql.append(" and DATE_FORMAT(creation_time,'%Y-%m-%d') = '" + DateFormatUtils.format(record.getCreationTime(), "yyyy-MM-dd") + "'");
            List<Map> rs = sqlManager.execute(new SQLReady(sql.toString()), Map.class);
            if(!rs.isEmpty()){
                sql = new StringBuilder("update statistics_financial set treat_transaction = IFNULL(treat_transaction,0) - 1 where id = :id");
                nq = em.createNativeQuery(sql.toString());
                nq.setParameter("id", rs.get(0).get("id"));
                nq.executeUpdate();
            }
        }
    }
}
